﻿using FluentValidation;
using SDF.Core.Data;
using SDF.Data;
using SDF.Plugin.Misc.SAPAdapter.Domain;
using SDF.Plugin.Misc.SAPAdapter.Models;
using SDF.Services.Localization;
using SDF.Web.Framework.Validators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SDF.Core;

namespace SDF.Plugin.Misc.SAPAdapter.Validators
{
    public class SAPClientModelValidator : BaseSDFValidator<SAPClientModel>
    {
        public SAPClientModelValidator(
            ILocalizationService localizationService,
            IDbContext dbContext,
            IRepository<SAPInstance> sapClientRepository
        )
        {
            #region

            RuleFor(x => x.Client)
               .NotEmpty()
               .WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.Client.Required"));

            RuleFor(x => x.CodeName)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.CodeName.Required"));

            RuleFor(x => x.Name)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.Name.Required"));

            RuleFor(x => x.User)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.User.Required"));

            RuleFor(x => x.Password)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.Password.Required"));

            RuleFor(x => x.SystemNumber)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.SystemNumber.Required"));

            RuleFor(x => x.SystemID)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.SystemID.Required"));

            #endregion

            RuleFor(x => x.ApplicationServer).Must((model, y) =>
            {
                if (model.IsGroupLogon)
                {
                    return model.MessageServerHost.IsNullOrEmpty() == false && model.LogonGroup.IsNullOrEmpty() == false;
                }
                else
                {
                    return model.ApplicationServer.IsNullOrEmpty() == false;
                }
            }).WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.ServerRequired"));

            RuleFor(x => x.CodeName).Must((model, x) =>
            {
                //CodeName不能重复
                return sapClientRepository.TableNoTracking.Any(p =>
                p.Id.Equals(model.Id) == false && p.CodeName.Equals(x) && p.Delete.Equals(false)) == false;

            }).WithMessage(localizationService.GetResource("Plugins.Misc.SAPAdapter.SAPInstance.CodeName.Unique"));

            SetStringPropertiesMaxLength<SAPInstance>(dbContext);
        }
    }
}